package org.kite;

import org.kite.processor.*;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;


public class App {
	public static void main(String[] args) throws Exception {

		List<String> lines = Arrays.asList("#	hello",
				"-	list1", "-	list2", "-	list3",
				"------");
		List<String> htmlLines = new ArrayList<>();

		ProcessorBase headProcessor = initProcessorChain();

		int offset = 0;
		while (lines.size() > offset) {

			//find the target processor
			ProcessorBase loopProcessor = headProcessor;
			MatchResult matchResult = loopProcessor.match(lines.get(offset));
			while (matchResult == null || matchResult == MatchResult.NotMatch) {
				loopProcessor = loopProcessor.getNextProcessor();
				matchResult = loopProcessor.match(lines.get(offset));
			}

			//add the first line
			List<String> mdBlocks = new ArrayList<String>();

			while (matchResult == MatchResult.MatchAndContinue) {
				mdBlocks.add(lines.get(offset));
				offset++;
				//find the markdown block for the processor
				matchResult = loopProcessor.match(lines.get(offset));
			}
			if (matchResult == MatchResult.Match) {
				mdBlocks.add(lines.get(offset));
				offset++;
			}

			// process the markdown block by the target processor and then add the result html to htmlLines list
			String htmlString = loopProcessor.process(mdBlocks);
			htmlLines.add(htmlString);

		}

		System.out.println("output:");
		for (String htmlLine : htmlLines) {
			System.out.println(htmlLine);
		}

	}

	// init all processors and make them a responsibility chain
	private static ProcessorBase initProcessorChain() {
		ProcessorBase processors[] = {
				new HeaderProcessor(),
				new UnorderedListProcessor(),
				new OrderedListProcessor(),
				new LinkProcessor(),
				new ImageProcessor(),
				new CodeInlineProcessor(),
				new CodeBlockProcessor(),
				new LineProcessor(),
				new TableProcessor(),
				new DefaultProcessor()
		};
		for (int i = 0; i < processors.length - 1; i++) {
			processors[i].setNextProcessor(processors[i + 1]);
		}
		return processors[0];
	}
}
